package za.org.jcicada.datastore.impl;

import java.util.Date;
import java.util.List;

import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.impl.MessagingBase;
import za.org.jcicada.datastore.IDataStoreClient;
import za.org.jcicada.datastore.IDataStoreServer;
import za.org.jcicada.datastore.messages.SensorHistoryReply;
import za.org.jcicada.datastore.messages.StatusHistoryReply;
import za.org.jcicada.genss.messages.Result;
import za.org.jcicada.genss.sensor.ISensorValue;
import za.org.jcicada.genss.sensor.SensorURN;
import za.org.jcicada.genss.sensor.impl.SensorStatusValue;

public class DataStoreMessaging extends MessagingBase {
    /**
     * Handle to dataStore server for invoking methods on.
     */
    IDataStoreServer dataStoreServer;

    /**
     * Handle to callback object for messages from the subject to the observer.
     */
    IDataStoreClient client;

    public DataStoreMessaging(IConnection connection, IDataStoreServer dataStoreServer) {
        super(connection);
        this.dataStoreServer = dataStoreServer;
        client = new Responder();
    }

    public void onClose() throws Exception {
        dataStoreServer.informDisconnect(client);
    }
    
    public IDataStoreClient getClient() {
    	return client;
    }

    public void datastoreSensorHistoryRequest(za.org.jcicada.datastore.messages.SensorHistoryRequest msg) {
        dataStoreServer.requestSensorHistory(client, msg.getSensorURN(), msg.getFrom(), msg.getTo());
    }
    
    public void datastoreStatusHistoryRequest(za.org.jcicada.datastore.messages.StatusHistoryRequest msg) {
    	dataStoreServer.requestStatusHistory(client, msg.getSensorURN(), msg.getFrom(), msg.getTo());
    }

    /**
     * Implementation of IDataStoreClient that sends messages back to a
     * comms connection.
     */
    public class Responder extends MessagingBase.ResponderBase implements IDataStoreClient {

        public void replySensorHistory(Result result, SensorURN sensorURN, Date from, Date to, List<ISensorValue> values) {
            sendMessage(new SensorHistoryReply(result, sensorURN, from, to, values));
        }
        
        public void replyStatusHistory(Result result, SensorURN sensorURN, Date from, Date to, List<SensorStatusValue> values) {
        	sendMessage(new StatusHistoryReply(result, sensorURN, from, to, values));
        }

    }
}
